let serverRand = "0123456789abcdef"
let pubk = "\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn8ICP+oVtkqgHIyET/n3\n" +
  "dgmDM1lmaU13PdKTfM169JAk08BdjIrmL60KiMCt0M7EV6DanO2O4tkhwhWByomn\n" +
  "x3YgU4vmku4l1BNZDh7tEDY3B/hVnZLpaC348uH2n8vc1SpEjAZSyxXTE/1wqMMW\n" +
  "Oi1mSFYIwc1GIHooq3VF1KF+3+Auzk3h/cUz9rYlf3ioWRj2iRD+Y4w2qRa6AKzy\n" +
  "ouWgnAL3nlcdSG38Kiiy0lJLB3xwv9dNxOA3/oJMNuUUkD5RtDuPoLUBUFdCHRGw\n" +
  "q4Czz0ElT2B072kNLdgzkUfu54XCAN8d3ggKFHLbdMTnS6k4IvRvsOCAnbnvfZIW\n" +
  "kQIDAQAB\n" //測試

// let pubk = "\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2YG3MXya+gCscnE2k5nJ\n" +
//   "tuMQS8LgXgamzRLtCKjBi86+i7Ljr3U0oBRbX6UX/ATXQ4+h4uxBBK0q6OwmqZSY\n" +
//   "vEAMJyAJNV4s8YWvT5+1ZgvGHZvCCBCBtrTydg+GA/yA02XjdfZrfPLUjk+KMPMS\n" +
//   "czHAeOwSALz/b6AxZVtboZ96g8ZliKPvcnHr2y9mDU1evysjpRb7iAlQBhOHke53\n" +
//   "jdvQx5dnwdT0Ctrnd/fK4bn9oMRC4A+0qB+KYAfKk8qQZDnOVXjYOaPo4zzIWsyE\n" +
//   "MKjxATMc36IQDZSpeTqu6rDX4uJbas/azNHaNuKuYnvKjR8FYulj9fh9QX80f6Xh\n" +
//   "EQIDAQAB\n" //生產

let CryptoJS = require("crypto-js")
let jsencrypt = require("jsencrypt")

/*
 ** randomWord 产生任意长度随机字母数字组合
 ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 ** xuanfeng 2014-08-28
 */
let randomWord = (range) => {
  let str = "",
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  for (let i = 0; i < range; i++) {
    let pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}

export default function() {
  let password = ""
  let getOriginPassword = (pwd) => {
    var pwdArray = pwd.split("")
    for (let i = 0; i < pwd.length; i++) {
      if (password.length > i && pwd[i] == "*") {
        pwdArray[i] = password[i]
      }
    }
    return pwdArray.join('');
  }

  this.encrypt = (pwd) => {
    password = getOriginPassword(pwd)
    let clientRand = randomWord(16)
    let keyHex = CryptoJS.enc.Utf8.parse(serverRand.substr(0, 12) + clientRand.substr(0, 12))
    let ivHex = CryptoJS.enc.Utf8.parse(serverRand.substr(12, 4) + clientRand.substr(12, 4))

    let encrypted = CryptoJS.TripleDES.encrypt(password, keyHex, {
      iv: ivHex
    })

    this.encryptedPassword = CryptoJS.enc.Base64.stringify(encrypted.ciphertext)

    var encrypt = new jsencrypt.JSEncrypt()
    encrypt.setPublicKey(pubk)
    this.encryptedClientRand = encrypt.encrypt(clientRand)

    this.mask = ""
    for (let i = 0; i < password.length; i++) {
      this.mask += "*"
    }
  }

  this.regexp = (exp) => {
    return exp.test(this.passowrd)
  }

  this.getPassword = () => {
    return CryptoJS.SHA1(password).toString()
  }
}
